package com.lsh.oms.core.proxy.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lsh.base.common.utils.RandomUtils;
import com.lsh.oms.core.enums.AbstractTaskType;
import com.lsh.oms.core.enums.RegionCode;
import com.lsh.oms.core.enums.SaleAreaCode;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.model.order.OrderDetail;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.proxy.AbstractAsyncTask;
import com.lsh.oms.core.service.tool.ToolService;
import com.lsh.oms.core.utils.HttpUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by panxudong on 16/12/23.
 */
@Component
public class RiskProxy {

    private static final String RISK_ORDER_CREATE_URL = "/api/rsm/java/v1/risk/order";
    private static Logger logger = LoggerFactory.getLogger(RiskProxy.class);
    @Value("${risk.host}")
    private String riskHost;

    public RiskProxy.RiskTask newAsyncTask(OrderHead orderHead, String logSign) {
        return new RiskTask(orderHead, logSign);
    }

    public boolean requestRiskCreateOrder(OrderHead orderHead, String logSign) {
        String riskUrl = riskHost + RISK_ORDER_CREATE_URL;

        Header[] headers = this.getHeaders();
        String requestString = this.getRiskBody(orderHead);

        String msg = " [RequestRiskCreateOrder][" + logSign + "]";
        logger.info(msg + "[start][Params:" + requestString);
        HttpMessage httpMessage;
        try {
            httpMessage = HttpUtils.sendPostRequest(riskUrl, requestString, headers);
            logger.info(msg + "[success]" + "[Return status:" + httpMessage.getStatus() + ", Return message:" + httpMessage.getMessage());
        } catch (Throwable e) {
            logger.error(msg + "[error]" + "[Error Class : " + e.getClass() + ", Error Message : " + e.getMessage() + "]");
            logger.error(e.getMessage(), e);
            return false;
        }

        return true;
    }

    private Header[] getHeaders() {
        Header[] headers = new Header[5];
        headers[0] = new BasicHeader("Content-type", "application/json; charset=utf-8");
        headers[1] = new BasicHeader("Accept", "application/json");
        headers[2] = new BasicHeader("api-version", "1.1");
        headers[3] = new BasicHeader("random", RandomUtils.randomStr2(32));
        headers[4] = new BasicHeader("platform", "oms");
        return headers;
    }

    private String getRiskBody(OrderHead orderHead) {
        List<Map<String, Object>> riskDetails = new ArrayList<>();
        List<OrderDetail> orderDetails = orderHead.getDetails();
        for (OrderDetail orderDetail : orderDetails) {
            Map<String, Object> riskDetail = new HashMap<>();
            riskDetail.put("sku_id", orderDetail.getGoodsCode());
            riskDetail.put("sale_unit", orderDetail.getGoodsSaleUnit());
            riskDetail.put("qty", orderDetail.getQuantity());
            riskDetail.put("type", orderDetail.getType());
            riskDetail.put("origin_price", orderDetail.getOriginalPrice());
            riskDetail.put("item_id", orderDetail.getSkuCode());
            riskDetails.add(riskDetail);
        }

        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("order_id", orderHead.getOrderCode());
        bodyMap.put("zone_id", orderHead.getRegionCode());
        bodyMap.put("province", orderHead.getProvince());
        bodyMap.put("city", orderHead.getCity());
        bodyMap.put("county", orderHead.getDistrict());
        bodyMap.put("address_id", orderHead.getAddressCode());
        bodyMap.put("area", orderHead.getArea());
        bodyMap.put("address_info", orderHead.getAddressInfo());
        bodyMap.put("ordered_at", orderHead.getOrderTime());
        bodyMap.put("uid", orderHead.getUserCode());
        bodyMap.put("storage_type", orderHead.getStorageType());

        String saleAreaCode = orderHead.getSaleAreaCode();

        if (orderHead.getRegionCode().compareTo(RegionCode.BEIJING.getCode()) == 0) {
            if (StringUtils.isBlank(saleAreaCode)) {
                saleAreaCode = SaleAreaCode.BQ.getCode();
            }
        }


        bodyMap.put("saleAreaCode", saleAreaCode);
        bodyMap.put("orderDetails", riskDetails);

        return JSON.toJSONString(bodyMap, ToolService.valueFilter, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero);
    }

    class RiskTask extends AbstractAsyncTask {
        private OrderHead orderHead;
        private String logSign;

        public RiskTask(final OrderHead orderHead, final String logSign) {
            super(AbstractTaskType.RISK_TASK);
            this.orderHead = orderHead;
            this.logSign = logSign;
        }

        @Override
        public void execute() {
            RiskProxy.this.requestRiskCreateOrder(orderHead, logSign);
        }
    }

}
